import React, { useEffect, useState, useMemo } from 'react';
import { Row, Col, Tooltip } from 'antd'
import 'echarts-gl'
import moment from "moment";
import AMapLoader from '@amap/amap-jsapi-loader';
import {Get, Url} from "../../server/http";
import { getVolumeByMB, getVolume, cpy } from "../../utils/cmn";
import Header from './Header'
import dianjunjie from "../../utils/cities/dianjunjie.json";
import aijia from "../../utils/cities/aijiazhen.json";
import qiaobian from "../../utils/cities/qiaobianzhen.json";
import lianpeng from "../../utils/cities/lianpengxiang.json";
import tucheng from "../../utils/cities/tuchengxiang.json";
import ItemCard from "../Screen/ItemCard";
import Title from "../Screen/Title";
import './index.less'


const mapKey = '3d944fa68cc341b006493f43d96bb16a';
const townList = {
	"七里村": {lng: '111.31556242', lat: '30.62558038'},
	"三岔口村": {lng: '111.06429536', lat: '30.68393117'},
	"三涧溪村": {lng: '111.08445597', lat: '30.70213578'},
	"上峰尖村": {lng: '111.16901417', lat: '30.74550512'},
	"五龙社区": {lng: '111.26774280', lat: '30.67389541'},
	"偏岩村": {lng: '111.23070699', lat: '30.70581096'},
	"六里河村": {lng: '111.16130760', lat: '30.66192350'},
	"刘家村": {lng: '111.34857625', lat: '30.62194719'},
	"双堰口村": {lng: '111.15002397', lat: '30.68074366'},
	"双溪村": {lng: '111.24964876', lat: '30.65847183'},
	"土城村": {lng: '111.11365619', lat: '30.65358401'},
	"塘上村": {lng: '111.25475310', lat: '30.67293822'},
	"天王寺村": {lng: '111.19297785', lat: '30.71231229'},
	"太平村": {lng: '111.21090159', lat: '30.68901720'},
	"安梓溪村": {lng: '111.13054759', lat: '30.61990689'},
	"巴王店村": {lng: '111.25053004', lat: '30.69800483'},
	"席家埫村": {lng: '111.02489807', lat: '30.71963662'},
	"新村村": {lng: '111.21166653', lat: '30.74126451'},
	"望洲坪村": {lng: '110.99700659', lat: '30.69869650'},
	"朱家坪村": {lng: '111.13712019', lat: '30.71778182'},
	"朱市街社区": {lng: '111.26683081', lat: '30.69498860'},
	"李家坝村": {lng: '111.11824480', lat: '30.66241993'},
	"李家河村": {lng: '111.25374329', lat: '30.71704854'},
	"李家湾村": {lng: '111.20182901', lat: '30.67808518'},
	"柳林村": {lng: '111.35605743', lat: '30.59220147'},
	"桥河村": {lng: '111.32307888', lat: '30.64306798'},
	"桥边村": {lng: '111.18969975', lat: '30.68026338'},
	"梅子溪社区": {lng: '111.27168642', lat: '30.66385332'},
	"楠木溪村": {lng: '111.23781533', lat: '30.62830825'},
	"泉水村": {lng: '111.18046755', lat: '30.63663089'},
	"牛扎坪村": {lng: '111.25562472', lat: '30.75324866'},
	"白马溪村": {lng: '111.19146575', lat: '30.66293335'},
	"石堰村": {lng: '111.21477147', lat: '30.70252037'},
	"福安村": {lng: '111.23706389', lat: '30.65387624'},
	"穿心店村": {lng: '111.07406326', lat: '30.65331199'},
	"紫阳村": {lng: '111.25289132', lat: '30.73273396'},
	"红光村": {lng: '30.67848676', lat: '111.28311010'},                        // 红光社区
	"联棚村": {lng: '111.27029983', lat: '30.64412036'},
	"至喜社区": {lng: '111.26310122', lat: '30.73599088'},
	"艾家村": {lng: '111.36806270', lat: '30.60390956'},
	"花栗树村": {lng: '111.12751351', lat: '30.69861972'},
	"范家湖村": {lng: '111.24532994', lat: '30.68896243'},
	"茅家店村": {lng: '111.08046026', lat: '30.63786576'},
	"落步埫村": {lng: '111.00975520', lat: '30.69418631'},
	"谭家河社区": {lng: '111.29546780', lat: '30.66362632'},
	"车溪村": {lng: '111.08927171', lat: '30.64288434'},
	"长岭村": {lng: '111.21082152', lat: '30.64932666'},
	"韩家坝村": {lng: '111.18191887', lat: '30.68070826'},
	"高岩村": {lng: '111.09391972', lat: '30.73630898'},
	"黄家岭村": {lng: '111.04971540', lat: '30.63772974'},
	"黄家棚村": {lng: '111.22233671', lat: '30.68544354'},
}

let dataTimer = null;       // 数据更新计时器
let switchTimer = null;     // 数据切换计时器 负责切换类型及区域
let globalUsageList = {};   // 记录全局数据
let mapObj = null;  // AMap对象
let map = null;     // 创建的地图实例
let flag = false;   // 第一次获取数据时开启一次窗口 后续窗口由切换区域开启

const Property = () => {
	const [assetData, setAsset] = useState([]);         // 资产统计信息
	const [resourceData, setResource] = useState([]);   // 资源统计信息

	useEffect(() => {
		getTownshipAsset();
		getTownshipResource();
		initMap()

		return () => {
			if (switchTimer !== null) {
				clearTimeout(switchTimer);
				switchTimer = null;
			}
			if (dataTimer !== null) {
				clearInterval(dataTimer);
				dataTimer = null;
			}
			globalUsageList = {};
			mapObj = null;  // AMap对象
			map = null;     // 创建的地图实例
			flag = false;
		}
	}, [])

	// 初始化地图
	const initMap = () => {
		AMapLoader.load({
			"key": mapKey,              // 申请好的Web端开发者Key，首次调用 load 时必填
			"version": "2.0",   // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
			"plugins": ['AMap.GeoJSON'],           // 需要使用的的插件列表，如比例尺'AMap.Scale'等
			"AMapUI": {             // 是否加载 AMapUI，缺省不加载
				"version": '1.1',   // AMapUI 缺省 1.1
				"plugins":[],       // 需要加载的 AMapUI ui插件
			},
			"Loca":{                // 是否加载 Loca， 缺省不加载
				"version": '2.0.0'  // Loca 版本，缺省 1.3.2
			},
		}).then((AMap)=>{
			mapObj = AMap;
			// getAllArea();
			creatMap();
		}).catch(e => {
			console.log(e);
		})
	}

	// 创建地图
	const creatMap = () => {
		map = new mapObj.Map('property-map', {
			zoom: 12.1,
			resizeEnable: true,
			pitch: 45,
			center: [111.169233, 30.672411],
			showBuildingBlock: true,
			showLabel: false,
			zoomEnable: true,   //是否缩放
			dragEnable: true,  //是否拖动
			mapStyle: "amap://styles/7049faf9a31244784b3c15dcf5c1f30d",
		});
		let dianjunGeo = new mapObj.GeoJSON({
			geoJSON: dianjunjie,
			// 还可以自定义getMarker和getPolyline
			getPolygon: function(geojson, lnglats) {
				return new mapObj.Polygon({
					path: lnglats,
					strokeColor: 'gray',
					fillColor: '#514dc7'
				});
			}
		});
		let aijiaGeo = new mapObj.GeoJSON({
			geoJSON: aijia,
			// 还可以自定义getMarker和getPolyline
			getPolygon: function(geojson, lnglats) {
				return new mapObj.Polygon({
					path: lnglats,
					strokeColor: 'gray',
					fillColor: '#314dc7'
				});
			}
		});
		let qiaobianGeo = new mapObj.GeoJSON({
			geoJSON: qiaobian,
			// 还可以自定义getMarker和getPolyline
			getPolygon: function(geojson, lnglats) {
				return new mapObj.Polygon({
					path: lnglats,
					strokeColor: 'gray',
					fillColor: '#814dc7'
				});
			}
		});
		let lianpengGeo = new mapObj.GeoJSON({
			geoJSON: lianpeng,
			// 还可以自定义getMarker和getPolyline
			getPolygon: function(geojson, lnglats) {
				return new mapObj.Polygon({
					path: lnglats,
					strokeColor: 'gray',
					fillColor: '#114dc7'
				});
			}
		});
		let tuchengGeo = new mapObj.GeoJSON({
			geoJSON: tucheng,
			// 还可以自定义getMarker和getPolyline
			getPolygon: function(geojson, lnglats) {
				return new mapObj.Polygon({
					path: lnglats,
					strokeColor: 'gray',
					fillColor: '#b14dc7'
				});
			}
		});
		map.add(dianjunGeo);
		map.add(aijiaGeo);
		map.add(qiaobianGeo);
		map.add(lianpengGeo);
		map.add(tuchengGeo);

		getAsset()
	}

	// 关闭区域信息窗口
	const closeWindow = () => {
		map.clearInfoWindow();
	}

	// 打开区域信息窗口
	const openWindow = (data, info) => {
		if (mapObj === null || map === null) {
			return ;
		}
		if (!data || !data['lng'] || !data['lat'])  {
			return ;
		}
		map.clearInfoWindow();
		let content = [];
		content.push(`<div style="font-size:16px;color:white;margin-left: 10px;height: 10px;">${data['title']}</div>`);
		content.push(`<span style="font-size:13px;color:white;margin-left: 10px;">资产情况&nbsp;&nbsp;${info['asset'] || '-'}元</span>`);
		content.push(`<span style="font-size:13px;color:white;margin-left: 10px;">资源情况&nbsp;&nbsp;${info['resource'] || '-'}亩</span>`);
		let infoWindow = new mapObj.InfoWindow({
			isCustom: true,  //使用自定义窗体
			content: createInfoWindow(content.join("<br/>")),
			offset: new mapObj.Pixel(82, 0),
		});
		infoWindow.open(map, new mapObj.LngLat(data['lng'], data['lat']));
	}

	// 创建窗体
	const createInfoWindow = (content) => {
		let info = document.createElement("div");
		info.className = "content-window-card";

		//可以通过下面的方式修改自定义窗体的宽高
		info.style.width = "250px";
		info.style.height = "150px";
		// 定义中部内容
		let middle = document.createElement("div");
		middle.className = "info-middle";
		middle.innerHTML = content;
		info.appendChild(middle);

		return info;
	}

	// 获取资产数据
	const getAsset = () => {
		Get(Url.ASSET_STATISTIC).then(
			data=>{
				let temp = {}
				for (let k in data) {
					let keyArr = k.split('/');
					if (keyArr && keyArr.length>0) {
						temp[keyArr[keyArr.length-1]] = {asset: data?.[k]?.[1] || 0}
					}
				}
				getResource(temp);
			}
		)
	}
	// 获取资源数据
	const getResource = (list) => {
		Get(Url.RESOURCE_STATISTIC).then(
			data=>{
				for (let k in data) {
					let keyArr = k.split('/');
					if (keyArr && keyArr.length>0) {
						list[keyArr[keyArr.length-1]]['resource'] = data?.[k]?.[1]
					}
				}

				for (let k in townList) {
					// const markerContent = `
					// 	<div class="custom-content-marker">
					// 		<img src="//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png">
					// 	</div>`
					const markerContent = `
						<div class="custom-content-marker">
							<div class="house-icon">
							</div>
						</div>`
					// const position = new mapObj.LngLat(temp['lon'], temp['lat']); //Marker 经纬度
					const position = new mapObj.LngLat(townList[k]['lng'], townList[k]['lat']); //Marker 经纬度
					const marker = new mapObj.Marker({
						position: position,
						content: markerContent, //将 html 传给 content
						offset: new mapObj.Pixel(-13, -30), //以 icon 的 [center bottom] 为原点
					});
					marker.on('mouseover', ()=>openWindow({lng: townList[k]['lng'],lat: townList[k]['lat'], title: k}, list[k] || {}))
					marker.on('mouseout', closeWindow)
					map.add(marker);


					// position: relative;
					// position: absolute;
					const style = {
						'position': 'absolute',
						'width': '8rem',
						'left': '-3rem',
						'top': '1.5rem',
						'background-color': 'rgba(0,0,0,0)',
						'border-width': 0,
						'text-align': 'center',
						'font-size': '18px',
						'color': 'white'
					};
					let text = new mapObj.Text({
						text: k,
						anchor:'center',
						style,
						position: [townList[k]['lng'], townList[k]['lat']]
					});
					text.setMap(map);
				}
			}
		)
	}

	// 按村镇获取数据并排序

	// 按村镇获取资产
	const getTownshipAsset = () => {
		Get(Url.ASSET_STATISTIC, ).then(
			data=>{
				console.log('data', data);
				let temp = []
				for (let k in data) {
					let name = ''
					name = k.split('/')
					name = name[name.length-1]
					temp.push({name, value: data[k]?.[1]})
				}
				temp.sort((a, b) => b.value - a.value)
				setAsset(temp);
			}
		)
	}
	// 按乡镇获取资源
	const getTownshipResource = () => {
		Get(Url.RESOURCE_STATISTIC).then(
			data=>{
				let temp = []
				for (let k in data) {
					let name = ''
					name = k.split('/')
					name = name[name.length-1]
					temp.push({name, value: data[k]?.[1]})
				}
				temp.sort((a, b) => b.value - a.value)
				setResource(temp);
			}
		)
	}



	// header高7vh
	return (
		<div className={'full-screen'}>
			<Header />
			<div className={'map-warp'}>
				<div id={'property-map'} className={'chinaMap'}/>
			</div>
			<div className={'property-layer-left'}>
				<Row style={{width: '100%', height: '89vh', marginTop: '1vh'}}>
					<ItemCard path={'base'}>
						<div style={{paddingTop: '1vh'}}>
							<Row type={'flex'}><Title title={'乡镇资产TOP'}/></Row>
							<div style={{width: '98%'}}>
								{
									assetData.map((item) => (
										<Row type={'flex'} style={{marginTop: '0.5vh', height: '1.8vh'}}>
											<Col span={7}>
												<Row type={'flex'} justify={'end'} style={{color: 'white', fontSize: '1.4vh'}}>
													{item['name']}：
												</Row>
											</Col>
											<Col span={16}>
												<Tooltip placement="top" title={item['value']+' 元'}>
													<div
														style={{
															height: '100%',
															width: item['value']/assetData[0]['value']*100+'%',
															backgroundColor: 'whitesmoke'
														}}
													/>
												</Tooltip>
											</Col>
										</Row>
									))
								}
							</div>
						</div>
					</ItemCard>
				</Row>
			</div>
			<div className={'property-layer-right'}>
				<Row style={{width: '100%', height: '89vh', marginTop: '1vh'}}>
					<ItemCard path={'base'}>
						<div style={{paddingTop: '1vh'}}>
							<Row type={'flex'}><Title title={'乡镇资源TOP'}/></Row>
							<div style={{width: '98%'}}>
								{
									resourceData.map((item) => (
										<Row type={'flex'} style={{marginTop: '0.5vh', height: '1.8vh'}}>
											<Col span={7}>
												<Row type={'flex'} justify={'end'} style={{color: 'white', fontSize: '1.4vh'}}>
													{item['name']}：
												</Row>
											</Col>
											<Col span={16}>
												<Tooltip placement="top" title={item['value']+' 亩'}>
													<div
														style={{
															height: '100%',
															width: item['value']/resourceData[0]['value']*100+'%',
															backgroundColor: 'whitesmoke'
														}}
													/>
												</Tooltip>
											</Col>
										</Row>
									))
								}
							</div>
						</div>
					</ItemCard>
				</Row>
			</div>
		</div>
	);
};

export default Property;
